package com.yinhe.music.yhmusic.video.list;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceViewPagerFragment;
import com.yinhe.music.yhmusic.comment.CommentListActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.model.MvsInfo;
import com.yinhe.music.yhmusic.music.PlayUtils;
import com.yinhe.music.yhmusic.search.ISearchFragment;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;
import com.yinhe.music.yhmusic.video.MvAdapter;
import com.yinhe.music.yhmusic.widget.CustomLoadMoreView;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.HeadItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;

import static com.yinhe.music.yhmusic.constants.IConstants.FAV_MV;
import static com.yinhe.music.yhmusic.constants.IConstants.SEARCH_MV;
import static com.yinhe.music.yhmusic.constants.IConstants.SINGER_DETAIL_MV;

/**
 * Created by hasee on 2017/2/25.
 */

public class MvFragment extends BaseServiceViewPagerFragment implements ISearchFragment,
        BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener,
        IMvListContract.IMvListView {

    @BindView(R.id.recommend_music_recyclerview)
    RecyclerView mRecyclerView;
    private int type;
    private int singerid;
    private int tagType;
    private String key;
    private MvAdapter mAdapter;
    private TextView mAlbumNum;
    private DividerItemDecoration itemDecoration;
    private LinearLayout mHeaderLayout;

    private MvsInfo collectMvInfo;

    private int pageNum;
    private int mPageSize = 10;
    private int mPage = 1;
    private int mvNum;

    private int itemPosition;

    MvListPresenter mPresenter;

    public static MvFragment newInstance(int from, String key) {
        MvFragment fragment = new MvFragment();
        Bundle bundle = new Bundle();

        bundle.putInt("type", from);
        bundle.putString("key", key);

        fragment.setArguments(bundle);
        return fragment;
    }

    public static MvFragment newInstance(int from, int id) {
        MvFragment fragment = new MvFragment();
        Bundle bundle = new Bundle();

        bundle.putInt("type", from);
        bundle.putInt("id", id);

        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            RxBus.get().unregister(this);
        }catch (Throwable e) {
            Log.e("RxBus解绑=============", e.toString());
        }
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MvListPresenter();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    @Override
    public void initView() {
        RxBus.get().register(this);

        if (getArguments() != null) {
            type = getArguments().getInt("type");
            singerid = getArguments().getInt("id", -1);
            key = getArguments().getString("key");
            tagType = getArguments().getInt("tags");
        }
        initAdapter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.music_hall_recycler_layout;
    }

    @Override
    protected void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        mPage = 1;
        reqMVList();
    }

    private void initAdapter() {
        mAdapter = new MvAdapter(key);

        mAdapter.setOnItemClickListener(this);
        mAdapter.setLoadMoreView(new CustomLoadMoreView());
        mAdapter.setOnLoadMoreListener(() -> {
            if (mPage <= pageNum) {
                reqMVList();
            } else {
                mAdapter.loadMoreEnd();
            }
        }, mRecyclerView);

        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        setRecyclerView();
    }

    private void setRecyclerView() {
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        mRecyclerView.setHasFixedSize(true);
        switch (type) {
            case FAV_MV:
                mRecyclerView.addItemDecoration(
                        new HeadItemDecoration(getActivity(),
                                getResources().getDimensionPixelOffset(R.dimen.dp_125)));
                mAdapter.addHeaderView(getHeadView(getLayoutInflater()));
                break;
            case SINGER_DETAIL_MV:
                itemDecoration = new DividerItemDecoration(getActivity(),
                        DividerItemDecoration.VERTICAL_LIST,
                        getResources().getDimensionPixelOffset(R.dimen.dp_125), false);
                mRecyclerView.addItemDecoration(itemDecoration);
                break;
            case SEARCH_MV:
                itemDecoration = new DividerItemDecoration(getActivity(),
                        DividerItemDecoration.VERTICAL_LIST,
                        getResources().getDimensionPixelOffset(R.dimen.dp_125), false);
                mRecyclerView.addItemDecoration(itemDecoration);
                mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                        super.onScrollStateChanged(recyclerView, newState);
                        if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                            RxBus.get().post(RxBusEventType.Search.HIDE_SOFT_KEYBOARD,
                                    RxbusNullObject.INSTANCE);
                        }
                    }
                });
                break;
        }
        mAdapter.setOnItemChildClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
    }

    private View getHeadView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.header_musiclist, (ViewGroup) mRecyclerView.getParent(), false);

        ImageView mPlayIcon = view.findViewById(R.id.play_icon);
        TextView mPlayText = view.findViewById(R.id.play_text);
        mHeaderLayout = view.findViewById(R.id.header_layout);
        mAlbumNum = view.findViewById(R.id.play_num);
        LinearLayout mManagerLayout = view.findViewById(R.id.manager);

        mHeaderLayout.setVisibility(View.GONE);
        mPlayIcon.setVisibility(View.GONE);
        mPlayText.setVisibility(View.GONE);
        mManagerLayout.setVisibility(View.GONE);
        return view;
    }

    private void reqMVList() {
        if (type == IConstants.SINGER_DETAIL_MV || type == IConstants.INSTRUMENT_MV) {
            mPresenter.getSingerMovieList(mPage, mPageSize, singerid, type);
        } else if (type == IConstants.SEARCH_MV) {
            mPresenter.getSearchList(mPage, mPageSize, key, type);
        } else if (type == IConstants.FAV_MV) {
            mPresenter.getCollectMovieList(mPage, mPageSize, type);
        } else if (type == IConstants.MORE_VIDEO || type == IConstants.NEW_MORE_MV) {
            mPresenter.getMovieList(mPage, mPageSize, tagType, type);
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        this.itemPosition = position;
        int mvId = ((MvsInfo) adapter.getData().get(position)).getMovieId();
        if (type == SEARCH_MV) UmengEventUtils.clickShare(getActivity(), UmengEventUtils.MV);
        PlayUtils.getMvInfo(mvId, getActivity());
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        collectMvInfo = (MvsInfo) adapter.getData().get(position);
        switch (view.getId()) {
            case R.id.mv_share:
                shareMv(collectMvInfo);
                break;
            case R.id.mv_collect:
                collectMv(position);
                break;
            case R.id.mv_comment:
                commentMv();
                break;
            default:
                break;
        }
    }

    private void shareMv(MvsInfo mvsInfo) {
        mPresenter.getShareInfo(IConstants.MOVIE, mvsInfo.getMovieId(), getActivity());
    }

    private void collectMv(int position) {
        if (!Preferences.getLoginSn().isEmpty()) {
            if (type == IConstants.FAV_MV) collectMvInfo.setCollectStatus(1);
            mPresenter.collectMv(collectMvInfo, position);
        } else {
            startLogin();
        }
    }

    private void commentMv() {
        Intent intent = new Intent(getActivity(), CommentListActivity.class);
        intent.putExtra("name", collectMvInfo.getMovieName());
        intent.putExtra("artist", collectMvInfo.getSingerName());
        intent.putExtra("cover", collectMvInfo.getImage());
        intent.putExtra("id", collectMvInfo.getMovieId());
        intent.putExtra("commentType", IConstants.MOVIE);
        startActivity(intent);
    }

    @Override
    public void updateDataForKey(String key) {
        if (key.equals(this.key)) return;

        this.key = key;
        if (mAdapter != null) {
            mAdapter.setSearchKey(key);
            mPage = 1;
            reqMVList();
        }
    }

    @Override
    public void setMvListUI(List<MvsInfo> list, int pageNum) {
        mRecyclerView.stopScroll();
        this.pageNum = pageNum;

        if (mPage == 1){
            mAdapter.setEmptyView(getEmptyView(mRecyclerView));
        }

        int size = list.size();
        if (mPage == 1) {
            mAdapter.setNewData(list);
        } else {
            if (size > 0) {
                mAdapter.addData(list);
            }
        }

        if (mPage >= pageNum) {
            mAdapter.loadMoreEnd();
        } else {
            mPage++;
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void updateCollectUI(MvsInfo mvsInfo, int position) {
        if (type == IConstants.FAV_MV) {
            mAdapter.remove(position);
            if (mvNum > 0) {
                mvNum --;
                mAlbumNum.setText(String.format(Locale.CHINESE, "收藏的MV(%d)", mvNum));
            }
        } else {
            mAdapter.setData(position, mvsInfo);
        }
    }

    @Override
    public void setCollectListHead(int num) {
        mvNum = num;
        mHeaderLayout.setVisibility(View.VISIBLE);
        mAlbumNum.setText(String.format(Locale.CHINESE, "收藏的MV(%d)", num));
    }

    /**
     * 更新收藏状态
     *
     * @param mvsInfo 不需要用到
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Mv.COLLECT_MV)}
    )
    public void onRxbusUpdateCollectState(MvsInfo mvsInfo) {
        try {
            mAdapter.getData().set(itemPosition, mvsInfo);
            mAdapter.notifyItemChanged(itemPosition);
        }catch (Throwable e) {
            Log.e("=============", e.toString());
        }
    }
}
